package com.itheima.exerciseTest.method30_39.method31;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

// 厨师类
public class Cooker implements Runnable {
    private Storefront sf;

    public Cooker(Storefront sf) {
        this.sf = sf;
    }

    private AtomicInteger ai = new AtomicInteger();
    private Semaphore sh = new Semaphore(1);

    @Override
    public void run() {
        while (true) {
            synchronized (sf) {
                // 判断今天面包做完了没，做完了就关门
                if (sf.getCount() >= sf.getNumber()) {
                    break;
                } else {
                    // 判断桌子上面包放满了没？
                    if (sf.getList().size() >= sf.getMaxisize()) {
                        // 厨师等待
                        try {
                            sf.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        // 厨师做
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        ai.getAndSet(sf.getCount());
                        sf.setCount(ai.incrementAndGet());
                        System.out.println(Thread.currentThread().getName() + "号厨师做好了第" + ai.get() + "个蛋糕");
                        sf.getList().add(ai.get());
                    }

                }
            }
        }
    }

}
